<?php
/**
 * 提问 
 *
 */
require_once 'lib/CException.php';
require_once 'services/IdCountService.php';
require_once 'services/QuestionService.php';
require_once 'services/TopicService.php';

class AskController extends Controller{

	public function index(){
		$this->_output['asset'] = 1;
		$user		=	 parent::getUser();

		if( empty( $user ) ){
			echo 'goto login page!';
			exit;
		}
		parent::render();	
	}

	/**
	 * 发表
	 */
	public function post(){
		$user		=	 parent::getUser();
		if( empty( $user ) ){
			echo 'goto login page!';
			exit;
		}

		$user_id     = $user['uid'];
		$options = array();
		$topic = parent::getRequest()->getParam('topic');
		if( is_array($topic ) ){
			foreach($topic as $key=>$val){
				$topic[$key] = str_replace(array(",", " "), "", $val);
			}
		}

		$idCountService = new IDCountService();
		$options['qid'] = $idCountService->generateId();
		$options['uid'] = $user_id;

		/* 连接入库展现需要转义 */
		$options['title']			 	= parent::getRequest()->getParam('title');
		$options['description'] = parent::getRequest()->getParam('description');
		$options['topic'] 			= @implode(",", $topic);
		$options['ip'] 					= ip2long( parent::getRequest()->getIp() );
		$options['status']  		= 1;

		if( !$options['qid'] ){
			throw new CException("id error", 500);
		}
		$questionService = new QuestionService();
		$ret = $questionService->create( $options );

		if( $ret == 0 ){
			echo 'question error';
			exit;
		}else{
			if( !empty($topic ) && count( $topic ) ){
				$params = array();
				$t_options['uid'] = $options['uid'];
				$t_options['qid'] = $options['qid'];

				foreach($topic as $vp){
					$t_options['tid'] = $idCountService->generateId();
					$t_options['name'] = $vp;
					$params[] = $t_options;
				}
				$topicService = new TopicService();
				$t_ret = $topicService->multi_create( $params );
			}
		}
		Header('location:/');
	}
}
